Date: March 3rd, 2020
Author: Bryan Rosales
Program: Intro to Machine Learning with TensorFlow

Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [1]:
# Python libraries to use in this project
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import time
import tensorflow as tf
import numpy as np
import pandas as pd
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import json
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow_hub as hub
from workspace_utils import active_session
In [2]:
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
In [3]:
# Display Tensorflow and Keras versions
print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 tf.keras version:', tf.keras.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')

# By default GPU workspace is disable, but once the network is built, I will use the GPU power to train it.
Using:
	• TensorFlow version: 2.0.0
	• tf.keras version: 2.2.4-tf
	• Running on GPU

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [4]:
# TODO: Load the dataset with TensorFlow Datasets.

splits = ['train','test','validation']

dataset, dataset_info = tfds.load('oxford_flowers102', split=splits, as_supervised=True, with_info=True)

# TODO: Create a training set, a validation set and a test set.
(training_set, testing_set, validation_set) = dataset
Downloading and preparing dataset oxford_flowers102 (336.76 MiB) to /root/tensorflow_datasets/oxford_flowers102/0.0.1...
/opt/conda/lib/python3.7/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
/opt/conda/lib/python3.7/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
/opt/conda/lib/python3.7/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)










WARNING:absl:Warning: Setting shuffle_files=True because split=TRAIN and shuffle_files=None. This behavior will be deprecated on 2019-08-06, at which point shuffle_files=False will be the default for all splits.
Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/0.0.1. Subsequent calls will reuse this data.

Explore the Dataset

In [5]:
# TODO: Get the number of examples in each set from the dataset info.
training_examples = dataset_info.splits['train'].num_examples
testing_examples = dataset_info.splits['test'].num_examples
validation_examples = dataset_info.splits['validation'].num_examples

print('Training Examples:   {:,}'.format(training_examples))
print('Testing Examples:    {:,}'.format(testing_examples))
print('Validation Examples: {:,}'.format(validation_examples))

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print('\nNumber of Classes: {:,}'.format(num_classes))
Training Examples:   1,020
Testing Examples:    6,149
Validation Examples: 1,020

Number of Classes: 102
In [6]:
# Dataset Metadata
dataset_info
Out[6]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    version=0.0.1,
    description='
The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
in the United Kingdom. Each class consists of between 40 and 258 images. The images have
large scale, pose and light variations. In addition, there are categories that have large
variations within the category and several very similar categories.

The dataset is divided into a training set, a validation set and a test set.
The training set and validation set each consist of 10 images per class (totalling 1030 images each).
The test set consist of the remaining 6129 images (minimum 20 per class).
',
    urls=['https://www.robots.ox.ac.uk/~vgg/data/flowers/102/'],
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    total_num_examples=8189,
    splits={
        'test': 6149,
        'train': 1020,
        'validation': 1020,
    },
    supervised_keys=('image', 'label'),
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
    redistribution_info=,
)
In [7]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
# Creates a plot with 1 row and 3 columns
fig, (ax1,ax2,ax3) = plt.subplots(figsize=(18,15) ,ncols=3 )
image1 = []
label1 = []

for image,label in training_set.take(3):    
    image = image.numpy()
    label = label.numpy()
    image1.append(image)
    label1.append(label)
    
ax1.imshow(image1[0])
ax1.set_title('Class: ' + str(label1[0]) + ', Shape: ' + str(np.array(image1[0]).shape))

ax2.imshow(image1[1])
ax2.set_title('Class: ' + str(label1[1]) + ', Shape: ' + str(np.array(image1[1]).shape))

ax3.imshow(image1[2])
ax3.set_title('Class: ' + str(label1[2]) + ', Shape: ' + str(np.array(image1[2]).shape))

# Images contain different shapes
Out[7]:
Text(0.5, 1.0, 'Class: 3, Shape: (711, 500, 3)')
In [166]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 

for image,label in training_set.take(25):    
    imgtf = image
    image = image.numpy()
    label = label.numpy()

plt.title('Class: ' + str(label))
plt.imshow(image)
Out[166]:
<matplotlib.image.AxesImage at 0x7fc103e866d0>

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [9]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)

print('Number of Classes',len(class_names))
Number of Classes 102
In [155]:
# Print the Class_name Dictionary

# for i in sorted (class_names.keys()) :  
#      print(i,class_names[i])   
In [165]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 

for image,label in training_set.take(8):    
    image = image.numpy()
    label = label.numpy()

plt.title('Class: ' + str(label) + ", Class_Name: " + class_names[str(label+1)])
plt.imshow(image)
Out[165]:
<matplotlib.image.AxesImage at 0x7fc103f213d0>

Image Resized Example

Since the images have different sizes, it is require to resize every image to (224, 224, 3) before training the network. The next is an example of original image vs a resized image.

In [88]:
IMAGE_SIZE = 224

#The function applies some transformations on the image to help out with Network Training and generalizing of the model
    #At least one of the transformation below will be applied.
def image_augmentation(img, label):
    x = np.random.randint(0, 4)
#     print('random: ',x)
    # Cases to apply transformations
    if x == 0:
        img = tf.image.rot90(img, k=np.random.randint(1, 4))
    elif x == 1:
        img = tf.image.random_flip_up_down(img)
        img = tf.image.random_flip_left_right(img, 42)
    elif x == 2:
        img = tf.image.random_hue(img, 0.08)
        img = tf.image.random_saturation(img, 0.6, 1.6)
        img = tf.image.random_brightness(img, 0.05)
        img = tf.image.random_contrast(img, 0.7, 1.3)
        
    img, label = image_preprocessing(img, label) 
    
    return img, label
                
# This function resizes the image to (224, 224, 3) and converts it to float32 and normalize the values between 0 and 1
def image_preprocessing(img, label):
    img = tf.image.resize(img, [IMAGE_SIZE, IMAGE_SIZE], method= tf.image.ResizeMethod.NEAREST_NEIGHBOR)
    img = tf.image.convert_image_dtype(img, dtype=tf.float32)
    
    return img, label
In [86]:
for image,label in training_set.take(1):
    label = label.numpy()
    image = image.numpy()
    new_image, label = image_preprocessing(image, label)
    
fig, (ax1,ax2) = plt.subplots(figsize=(15,10) , ncols=2)
ax1.imshow(image)
ax1.set_title('Original Image ' + str(image.shape) + ', Class_Name: ' + class_names[str(label+1)])

ax2.imshow(new_image)
ax2.set_title('Resized Image ' + str(new_image.shape) + ', Class_Name: ' + class_names[str(label+1)])
print('Org Img: ', image.shape)
print('New Img: ', new_image.shape)
Org Img:  (752, 500, 3)
New Img:  (224, 224, 3)

Testing image_augmentation()

The following code compare images after preprocessing and transformation (original vs. transformed).

In [167]:
fig = plt.figure(figsize= (12, 25))
n=1
rows = 4
cols = 2

for image,label in training_set.take(4):
    image1, label1 = image_augmentation(image, label)
    label = label.numpy()
    label1 = label1.numpy()
    
    # Plot Original Image
    fig.add_subplot(rows, cols, n)
    plt.imshow(image)
    plt.title('Original, Class: ' + class_names[str(label+1)] + ', Shape:' + str(tf.shape(image).numpy()))
    n+=1
    
    # Plot transformed Image
    fig.add_subplot(rows, cols, n)
    plt.imshow(image1)
    plt.title('Transformed, Class: ' + class_names[str(label1+1)] + ', Shape:' + str(tf.shape(image1).numpy()))    
    n+=1

Create Pipeline

Training Dataset

Since our training set only contains 1,020 images, I will use the function image_augmentation() to make some transformations to the images in order to augment the dataset and help our network out to generalize the data correctly.

In [89]:
# In order to fit the data to the model, it is necessary to create a pipeline keeping in mind processing times of the operations I am performing on the images. In this case, I am using batches 64 images. 

batch_size = 64

training_batches = training_set.shuffle(training_examples//4).map(image_augmentation).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(image_preprocessing).batch(batch_size).prefetch(1)
testing_batches = testing_set.map(image_preprocessing).batch(batch_size).prefetch(1)

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [90]:
# Model chosen is MobileNet v2.0 features vector 

URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
pretrained_model = hub.KerasLayer(URL, trainable=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))


# pretrained_model = tf.keras.applications.MobileNetV2(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), include_top = False,
#                                               weights='imagenet', alpha=1.4)
# pretrained_model.trainable = False
In [95]:
# Model Arquitecture

model = tf.keras.Sequential([
    pretrained_model,
    tf.keras.layers.Dense(1024, activation='relu'),
    tf.keras.layers.Dropout(0.3),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dropout(0.3),
    tf.keras.layers.Dense(102, activation='softmax')       
])

model.summary()

# Model Optimization
model.compile(
    optimizer= 'adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
Model: "sequential_13"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer_1 (KerasLayer)   (None, 1280)              2257984   
_________________________________________________________________
dense_41 (Dense)             (None, 1024)              1311744   
_________________________________________________________________
dropout_11 (Dropout)         (None, 1024)              0         
_________________________________________________________________
dense_42 (Dense)             (None, 512)               524800    
_________________________________________________________________
dropout_12 (Dropout)         (None, 512)               0         
_________________________________________________________________
dense_43 (Dense)             (None, 102)               52326     
=================================================================
Total params: 4,146,854
Trainable params: 1,888,870
Non-trainable params: 2,257,984
_________________________________________________________________
In [26]:
# Model Evaluation before Training
loss, accuracy = model.evaluate(testing_batches)
97/97 [==============================] - 16s 162ms/step - loss: 4.6754 - accuracy: 0.0094
In [98]:
EPOCHS = 10

early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 3)
best_model = tf.keras.callbacks.ModelCheckpoint('./models/best_model.h5', monitor='val_loss', save_best_only=True)

# Define the Keras TensorBoard callback.
#log_dir = "./logs/fit/"
#tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)

#with active_session():
history = model.fit(training_batches, 
                    epochs=EPOCHS, 
                    validation_data=validation_batches, 
                    callbacks=[best_model])
Epoch 1/10
16/16 [==============================] - 6s 353ms/step - loss: 0.2247 - accuracy: 0.9441 - val_loss: 0.0000e+00 - val_accuracy: 0.0000e+00
Epoch 2/10
16/16 [==============================] - 6s 354ms/step - loss: 0.1908 - accuracy: 0.9451 - val_loss: 0.8523 - val_accuracy: 0.7824
Epoch 3/10
16/16 [==============================] - 6s 349ms/step - loss: 0.1846 - accuracy: 0.9510 - val_loss: 0.8071 - val_accuracy: 0.7853
Epoch 4/10
16/16 [==============================] - 5s 332ms/step - loss: 0.1589 - accuracy: 0.9608 - val_loss: 0.8115 - val_accuracy: 0.7755
Epoch 5/10
16/16 [==============================] - 6s 348ms/step - loss: 0.1250 - accuracy: 0.9686 - val_loss: 0.7871 - val_accuracy: 0.7912
Epoch 6/10
16/16 [==============================] - 5s 333ms/step - loss: 0.1282 - accuracy: 0.9627 - val_loss: 0.8419 - val_accuracy: 0.7745
Epoch 7/10
16/16 [==============================] - 6s 349ms/step - loss: 0.1020 - accuracy: 0.9735 - val_loss: 0.7785 - val_accuracy: 0.8049
Epoch 8/10
16/16 [==============================] - 5s 332ms/step - loss: 0.1003 - accuracy: 0.9706 - val_loss: 0.8191 - val_accuracy: 0.7873
Epoch 9/10
16/16 [==============================] - 5s 333ms/step - loss: 0.0913 - accuracy: 0.9784 - val_loss: 0.7976 - val_accuracy: 0.8010
Epoch 10/10
16/16 [==============================] - 5s 331ms/step - loss: 0.0749 - accuracy: 0.9765 - val_loss: 0.8060 - val_accuracy: 0.7990
In [99]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(EPOCHS)
# print(epochs_range)
plt.figure(figsize=(15, 5))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower left')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [100]:
# TODO: Print the loss and accuracy values achieved on the entire test set.

# Model Evaluation before Training
new_loss, new_accuracy = model.evaluate(testing_batches)
97/97 [==============================] - 14s 140ms/step - loss: 0.8992 - accuracy: 0.7744

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [156]:
model_filepath = './models'
tf.saved_model.save(model, model_filepath)

Load the Keras Model

Load the Keras model you saved above.

In [157]:
# Load the Keras model saved previously
model_filepath = './models'
reloaded_model = tf.keras.models.load_model(model_filepath)

reloaded_model.summary()
Model: "sequential_13"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer_1 (KerasLayer)   (None, 1280)              2257984   
_________________________________________________________________
dense_41 (Dense)             (None, 1024)              1311744   
_________________________________________________________________
dropout_11 (Dropout)         (None, 1024)              0         
_________________________________________________________________
dense_42 (Dense)             (None, 512)               524800    
_________________________________________________________________
dropout_12 (Dropout)         (None, 512)               0         
_________________________________________________________________
dense_43 (Dense)             (None, 102)               52326     
=================================================================
Total params: 4,146,854
Trainable params: 1,888,870
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [158]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
test_image = tf.convert_to_tensor(test_image)

processed_test_image, label = image_preprocessing(test_image, 0)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [159]:
# TODO: Create the predict function

def predict(image_path, model, top_k):
    img = np.asarray(Image.open(image_path))
    img = tf.convert_to_tensor(img)
    img, label = image_preprocessing(img, 0)
    img_batch = tf.reshape(img, [1, IMAGE_SIZE, IMAGE_SIZE, 3])
    probs = model.predict(img_batch)
    probs = probs.flatten()    
    ps, classes = tf.math.top_k(probs, k=top_k, sorted=True)
    ps = ps.numpy()
    classes = classes.numpy()
   
    return ps, classes, img
In [168]:
# Testing Predict() function

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
ps, classes, img = predict(image_path, reloaded_model, 5)
print(ps, type(ps[0]))
print(classes, type(classes[0]))
[9.9999797e-01 1.1875821e-06 2.7439660e-07 1.8970444e-07 1.2886960e-07] <class 'numpy.float32'>
[ 1  6 12 79 19] <class 'numpy.int32'>

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [161]:
# TODO: Plot the input image along with the top 5 classes
import os

TOP_K = 5


dir_path = './test_images/'
for img_filename in os.listdir(dir_path):
    ps, classes, img = predict(dir_path + img_filename, reloaded_model, TOP_K)
    labels =[]
    for l in classes:
        labels.append(class_names[str(l+1)]) 

    
    fig, (ax1, ax2) = plt.subplots(figsize=(10,9), ncols=2)
    ax1.imshow(img)
    ax1.axis('off')
    ax1.set_title(img_filename)
    ax2.barh(np.arange(TOP_K), ps)
    ax2.set_aspect(0.1)
    ax2.set_yticks(np.arange(TOP_K))
    ax2.set_yticklabels(labels, size='small');
    ax2.set_title('Class Probability')
    ax2.set_xlim(0, 1.1)
    plt.tight_layout()